<template>
  <div id="work-wechat-index">
    <div class="top-search">
      <van-search v-model="json.search.keyword" placeholder="请输入商品名称" @search="search" shape="round"></van-search>
    </div>
    <div>
      <div @click="classificationOfSwitch()" style="padding-top: 15px; padding-bottom: 15px; position: relative;">
        <!-- <van-field v-model="fieldValue" is-link readonly :label="category_text" placeholder="请选择所在地区" @click="show = true" /> -->
        <div class="nav">
          <span class="m-r10 choose" @click.stop="CategoryShow=true">{{category_text}}<van-icon name="arrow-down" /></span>
          <span class="m-r10 choose" @click.stop="store_Show=true" v-if="radio!==0 && radio!==''">{{choose_text}}<van-icon name="arrow-down" /></span>
          <span style="margin: 1rem;" @click.stop="popupShow=true">{{fieldValue}}</span>
        </div>
        <van-icon name="arrow" />
      </div>
    </div>
    <div class="list" v-if="goodsList.length > 0">
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" :immediate-check="false" @load="loadMore">
        <div class="goods-item" v-for="(goods) in goodsList" :key="goods.id" @click.stop="toGoodsDetail(goods.id)">
          <div class="left-img">
            <img :src="goods.thumb" alt="">
          </div>
          <div class="right-info overflow">
            <h1 class="goods-title overflow">{{goods.title}}</h1>
            <p class="price">{{$i18n.t('money')}} {{goods.price}}</p>
            <div class="bottom">
              <span class="stock">库存{{goods.stock}}</span>
              <div class="bnt-send" @click.stop="sendGoods(goods)">发送</div>
            </div>
          </div>
        </div>
      </van-list>
    </div>
    <van-empty v-else description="空空如也"></van-empty>
    <div class="classificationPopUps">
      <van-popup v-model="popupShow" round position="bottom">
        <van-cascader v-model="cascaderValue" title="请选择分类" :options="options" @close="popupShow = false"
          :field-names="fieldNames" @finish="onFinish" />
      </van-popup>
    </div>
    <van-popup v-model="CategoryShow" round position="bottom">
        <div class="flex between align-center popup-top">
          <span @click="CategoryShow=false" class='pointer'>取消</span>
          <span>选择类型</span>
          <span class="c-FF2F2F pointer" @click="confirmCategory('category')" >确认</span>
        </div>
        <van-radio-group v-model="radio" checked-color="#F43629">
          <van-cell-group>
            <van-cell v-for="item in category_list" :key="item.id"  :title="item.name" clickable>
              <template #right-icon>
                <van-radio :name="item.id" />
              </template>
            </van-cell>
          </van-cell-group>
        </van-radio-group>
      </van-popup>
    <van-popup v-model="store_Show" round position="bottom" :style="{height:'45%'}">
        <div class="flex between align-center popup-top">
          <span @click="store_Show=false" class='pointer'>取消</span>
          <span>{{choose_text}}</span>
          <span class="c-FF2F2F pointer" @click="confirmCategory" >确认</span>
        </div>
        <!-- <input
          v-model="search_keyword"
          placeholder="请输入搜索关键词"
          @change="onSearch"
          /> -->
        <van-search
          v-model="search_keyword"
          show-action
          shape="round"
          placeholder="请输入搜索关键词"
          @search="onSearch"
        >
          <template #action>
            <van-button round size="small" @click="onSearch" color="#F43629" >搜索</van-button>
          </template>
        </van-search>
        <van-radio-group v-model="plugin_id" checked-color="#F43629">
          <van-cell-group>
            <van-cell v-for="item in plugin_data" :key="item.id"  :title="item.name" clickable>
              <template #right-icon>
                <van-radio :name="item.id" />
              </template>
            </van-cell>
          </van-cell-group>
        </van-radio-group>
      </van-popup>
  </div>
</template>

<script>
  import {
    Cascader
  } from 'vant';
  Vue.use(Cascader);
  export default {
    data() {
      return {
        agentData: { // 企业微信config接口配置
          agent_secret: "",
          agentid: "",
          corpid: ""
        },
        strUrl: "plugin.wechat-chat-sidebar.frontend.controller.customer.home-page.index",
        getConfig: {
          client: 'work',
          type: 17
        }, //企业微信公共参数
        goodsList: [],
        json: {
          page: 1,
          search:{
            keyword: '',
            category:''
          }
        },
        cropId:'',
        loading: false,
        finished: false,
        sendGoodsData: '',
        options: [], //分类数据显示
        cascaderValue: '',
        popupShow: false, //分类弹窗显示
        fieldNames: {
          text: 'name',
          value: 'id',
          children: 'has_many_children',
        },
        fieldValue: '选择分类',
        CategoryShow:false,
        radio:"",
        category_list:[],
        category_text:"选择类型",
        choose_text:"选择门店",
        store_Show:false,
        search_keyword:"",
        plugin_id:"",
        plugin_data:[],
        timeId:null,
        type:'',//酒店、门店、商品类型
      };
    },

    activated() {
      if (this.fun.getKey("crop_id")) {
        let corp_id = this.fun.getKey("crop_id");
        window.localStorage.setItem("crop_id", corp_id);
        this.cropId = corp_id;
      } else {
        console.log(window.localStorage.getItem("crop_id"));
        this.cropId = window.localStorage.getItem("crop_id") || '0';
      }
      this.getAgentConfig();
      this.categoricalData()
      this.get_category()
    },
    methods: {
      async  getHotelData(shop = ''){
        if(this.json.search.keyword == ''){ //如果搜索框没有值就不传keyword
          delete this.json.search['keyword']
        }
        if(this.json.search.category == ''){ //如果分类没有选择就不传category
          delete this.json.search['category']
        }
        this.json.search.plugin_id=33;
        this.json.page = 1;
        if(this.radio!==0){
          this.json.search.plugin_data_id = this.plugin_id;
        }
        if(shop == 'shop'){
          this.json.search.plugin_id = 0;
        }
        let {result,msg,data} = await $http.post('plugin.wechat-chat-sidebar.frontend.controller.customer.home-page.index',{...this.json,...this.getConfig});
        if(result==0){
          return this.$toast(msg);
        }
        this.goodsList =  data.data;
        this.json.page = 2;
      },
      async get_category_data(){
        console.log('进get_category_data')
        this.cascaderValue = '';
        let json = {
          client:'work',
          type:17,
          plugin_type:this.radio
        }
        if(this.radio!==0){
          json.plugin_data_id = this.plugin_id;
        }
        let {data,result,msg} =   await $http.get("plugin.wechat-chat-sidebar.frontend.controller.customer.home-page.get-category",json)
        if(result == 0){
          this.$toast(msg)
        }else{
          this.options = this.filterArr(data);
          console.log(this.options," this.options");
          if(this.radio == 0){
            this.getHotelData('shop');
          }else{
            this.getHotelData();
          }
        }
      },
      filterArr(data){
        data.forEach(item => {
        if (item.has_many_children && item.has_many_children.length !== 0) {
          this.filterArr(item.has_many_children);
        } else if ( item.has_many_children && item.has_many_children.length == 0) {
          delete item.has_many_children;
        }
      });
      return data;
    },
      onSearch(){
          this.get_store_data()
      },
      async get_store_data(){
        this.cascaderValue = '';
        let json = {
          client:'work',
          type:17,
          plugin_id:this.radio
        }
        if(this.search_keyword){
          json.keyword = this.search_keyword;
        }
        let {result,data,msg} = await $http.get('plugin.wechat-chat-sidebar.frontend.controller.customer.home-page.get-plugin-data',json);
        if(result == 0){
          return this.$toast(msg);
        }else{
          this.plugin_data = data;
          this.getHotelData()
        }
      },
     async  get_category(){
        let {result,data,msg} = await $http.get('plugin.wechat-chat-sidebar.frontend.controller.customer.home-page.get-category-type',{client:"work",type:17});
        if(result == 1){
          this.category_list = data
        }else if(result ==0){
          this.$toast(msg)
        }
      },
      confirmCategory(type){
        this.type = type;//选择类型
        if(type == 'category'){
          this.CategoryShow = false;
          this.category_list.map(item => {
            if(item.id == this.radio){
              this.category_text=item.name+'分类';
              if(this.radio == 32){
                   this.choose_text="选择门店分类";
                   return;
              }
                this.choose_text='选择'+item.name;
            }
          })
          if(this.radio !== 0){
            this.store_Show = true;
            this.get_store_data()
            return;
          }
          console.log('this.radio',this.radio)
          this.get_category_data()
        }else{
          this.plugin_data.map(item => {
            if(item.id == this.plugin_id){
              this.choose_text = item.name;
            }
          })
          this.store_Show=false;
          this.get_category_data()
          this.getHotelData()
        }
      },
      //分类弹窗切换
      classificationOfSwitch() {

        // this.CategoryShow = !this.CategoryShow;

        this.popupShow = !this.popupShow
      },
      onFinish(e) {
        this.popupShow = false;
        this.fieldValue = e.selectedOptions.map((option) => option.name).join('/');
        this.json.search.category = e.value
        this.getData()
      },
      // 企业微信配置信息
      getAgentConfig() {
        let that = this;
        $http
          .get("plugin.wechat-chat-sidebar.frontend.controller.index.get-config", {
            crop_id:this.cropId,url: this.fun.isIosOrAndroid() === "ios" ? window.initUrl : document.location.href
          }, "loading")
          .then(response => {
            if (response.result === 1) {
              this.agentData = response.data;
              let get_token = response.data.get_token;
              let config = {
                debug: false,
                beta: true,
                jsApiList: ["agentConfig"],
                openTagList: ["ww-open-data"],
                appId: this.agentData.corpid,
                nonceStr: get_token.noncestr,
                timestamp: get_token.timestamp,
                signature: get_token.token
              };
              wx.config(config);
              wx.ready(() => {
                setTimeout(() => {
                  that.getAgentSign(config, get_token.app_token);
                }, 500);
              });
              wx.error(res => {
                this.$toast("config信息验证失败！" + JSON.stringify(res));
                // console.log("getAgentConfig：：config信息验证失败！" + JSON.stringify(res));
              });
            } else {
              this.$toast(response.msg);
            }
          })
          .catch(error => {
            console.log("getAgentConfig::", error);
          });
      },
      // 企业微信登录
      getAgentSign(config, app_token) {
        // let that = this;
        wx.agentConfig({
          corpid: config.appId,
          agentid: this.agentData.agentid,
          timestamp: config.timestamp,
          nonceStr: config.nonceStr,
          signature: app_token,
          jsApiList: ["sendChatMessage"],
          success: () => {
            this.getData();
          }
        });
      },
      async getData(e) {
        if (this.finished && this.loading) {
          return;
        }
        if(e != 'loadMore'){ //如果不是下拉刷新page为1
          this.json.page = 1
        }
        if(this.json.search.keyword == ''){ //如果搜索框没有值就不传keyword
          delete this.json.search['keyword']
        }
        if(this.json.search.category == ''){ //如果分类没有选择就不传category
          delete this.json.search['category']
        }
        if(this.radio === ''){
          delete this.json.search.plugin_id;
          delete this.json.search.plugin_data_id;
        }
        try {
          this.loading = true;
          this.finished = false;
          let res = await $http.post(this.strUrl, {
            ...this.json,
            ...this.getConfig
          }, "loading");
          this.loading = false;
          if (res.result === 1) {
            if (this.json.page >= res.data.last_page || res.data.data.length < res.data.per_page) {
              this.finished = true;
            }
            this.goodsList = this.json.page > 1 ? this.goodsList.concat(res.data.data) : res.data.data;
            this.json.page = ++this.json.page;
          } else {
            this.finished = true;
            this.$toast(res.msg != "" ? res.msg : "暂无数据");
          }
        } catch (err) {
          this.loading = false;
          console.log(err);
        }
      },
      search() {
        this.json.page = 1;
        this.loading = false;
        this.finished = false;
        this.getData();
      },
      loadMore() {
        this.getData('loadMore');
      },
      sendGoods(data) {
        let goods = data;
        if(data.appid){
          console.log(goods.thumb,'改成发送小程序')
          // appid有内容，改成发送小程序
          wx.invoke('sendChatMessage', {
            msgtype: "miniprogram",
            miniprogram: {
              appid: goods.appid, //小程序的appid，企业已关联的任一个小程序
              title: goods.title, //小程序消息的title
              imgUrl: goods.thumb, //小程序消息的封面图。
              page: "/packageA/detail_v2/detail_v2.html?id="+goods.id //小程序消息打开后的路径，注意要以.html作为后缀，否则在微信端打开会提示找不到页面
            }
          }, function(res) {
            if (res.err_msg == 'sendChatMessage:ok') {
              //发送成功
              console.log("sendChatMessage::ok", res);
            }
          });
          return
        }
        console.log(goods);
        wx.invoke('sendChatMessage', {
          msgtype: "news", //消息类型，必填
          enterChat: true, //为true时表示发送完成之后顺便进入会话，仅移动端3.1.10及以上版本支持该字段
          text: {
            content:"你好", //文本内容
          },
          news: {
            link: goods.link, //H5消息页面url 必填
            title: goods.title ? goods.title : '商品', //H5消息标题
            desc: goods.has_one_share && goods.has_one_share.share_desc || '分享', //H5消息摘要
            // imgUrl: "https://" + goods.thumb, //图片地址 图片地址为必填且要符合网络地址规律
            imgUrl: goods.thumb,
          },
        }, function(res) {
          if (res.err_msg == 'sendChatMessage:ok') {
            //发送成功
            console.log("sendChatMessage::ok", res);
          }
        });
      },
      categoricalData() { //获取分类数据
        $http.get("plugin.wechat-chat-sidebar.frontend.controller.customer.home-page.get-category", this.getConfig,
            "loading")
          .then(response => {
            if (response.result === 1) {
              this.options = response.data
              this.options.forEach((item, index) => {
                if (item.has_many_children.length == 0) {
                  delete this.options[index]['has_many_children']
                }
              })
            } else {
              this.$toast(response.msg);
            }
          })
          .catch(error => {
            console.log("getAgentConfig::", error);
          });
      },
      toGoodsDetail(gid) {
        this.$router.push(this.fun.getUrl("goods", {
          id: gid
        }));
      }
    },
    watch:{
      search_keyword(){
        if(this.timerId){clearTimeout(this.timeId)};
        this.timeId = setTimeout(() => {
          this.get_store_data()
        }, 500);
      }
    },
    components: {},
  };
</script>
<style lang='scss' rel='stylesheet/scss' scoped>
::v-deep .van-icon-arrow-down {
  margin-left: 0.3rem;
}

::v-deep .van-icon-arrow {
  position: absolute;
  top: 50%;
  right: 0.6rem;
  transform: translateY(-50%);
}

::v-deep .van-button {
  width: 4.4rem;
}

::v-deep .van-cell::after {
  border-bottom: unset;
}

::v-deep .van-cell__title {
  text-align: left;
}

#work-wechat-index {
  .pointer {
    cursor: pointer;
  }

  font-size: 12px;

  .choose {
    background: #f8f8f8;
    padding: 0.5rem;
    margin: 0.5rem;
  }

  .nav {
    background-color: #fff;
    text-align: left;
    display: flex;
    flex-wrap: wrap;
  }

  .m-r10 {
    margin-right: 0.3125rem;
  }

  .popup-top {
    padding: 1.125rem 0.875rem;
  }

  .c-FF2F2F {
    color: #ff2f2f;
  }

  .flex {
    display: flex;
  }

  .between {
    justify-content: space-between;
  }

  .align-center {
    align-items: center;
  }

  .top-search {
    background-color: #fff;
    padding: 0.43rem 0.96rem;
  }

  .list {
    padding: 0.43rem 0.96rem;
    background-color: #f2f2f2;

    .goods-item {
      display: flex;
      align-items: center;
      padding: 0.81rem;
      background-color: #fff;
      border-radius: 0.25rem;

      .left-img {
        width: 4.688rem;
        height: 4.688rem;
        border-radius: 0.25rem;

        img {
          width: 100%;
          height: 100%;
        }
      }

      .right-info {
        flex: 1;
        text-align: left;
        margin-left: 0.5rem;

        .goods-title {
          font-size: 14px;
          color: #202020;
        }

        .price {
          margin: 0.5rem 0;
          font-size: 0.75rem;
          color: #f14e4e;
        }

        .bottom {
          display: flex;

          .stock {
            flex: 1;
            color: #999;
          }

          .bnt-send {
            color: #fff;
            padding: 0.25rem 1.125rem;
            background-color: #f78b00;
            border-radius: 0.125rem;
          }
        }
      }
    }
  }
}
</style>
